package com.zzh.begui;

import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class login extends JFrame {

	private JLabel labUser=new JLabel("User:",JLabel.RIGHT);
	private JLabel labPwd=new JLabel("PWD:",JLabel.RIGHT);
	private JTextField txtUser=new JTextField();
	private JTextField txtPwd=new JTextField();
	private JButton btnOK=new JButton("OK");
	private JButton btnCancel=new JButton("Cancel");
	//链接DB，查看user,password是否正确
	Connection con;
	//驱动程序名
	String driver="com.mysql.jdbc.Driver";
	//URL指向要访问的数据库名
	String url="jdbc:mysql://localhost:3306/z_miand";
	String user="root";
	String password="zhou2851";
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
	    new login();
	}

	/**
	 * Create the frame.
	 */
	public login() {
		setSize(362,312);
		setLocation(300,300);
		setTitle("Login");
		getContentPane().setLayout(null);
		getContentPane().add(labUser); labUser.setBounds(50,50,80,25);
		getContentPane().add(txtUser); txtUser.setBounds(135,50,120,25);
		getContentPane().add(btnOK); btnOK.setBounds(90,125,80,25);
		
		getContentPane().add(labPwd); labPwd.setBounds(50,85,80,25);
		getContentPane().add(txtPwd); txtPwd.setBounds(135,85,120,25);		
		getContentPane().add(btnCancel);btnCancel.setBounds(175,125,80,25);
		btnEvent();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
		//setBounds(100, 100, 450, 300);
		
	}
    private void btnEvent(){
    	btnOK.addActionListener(new ActionListener(){
    		public void actionPerformed(ActionEvent e){
    			/*检查user和password的值与DB中表的数据是否一样，如是直接进入主窗体
    			 * catch(ClassNotFoundException e){
    				System.out.println("Soryy,can't find the Driver!");
    				e.printStackTrace();
    			}
    			 * 
    			 * */
    			String strUser=txtUser.getText();
    			String strPwd=txtPwd.getText();
    			//查看用户名，密码是否正确
    			try{
    				//加载驱动程序
    				Class.forName(driver);
    				con=DriverManager.getConnection(url,user,password);
    				if(!con.isClosed())
    					System.out.println("successed connectiong to the database!");
    				Statement statement =con.createStatement();
    				String sql="select name,pwd from z_user";
    				ResultSet rs=statement.executeQuery(sql);
    				System.out.println("-----------------");
    				System.out.println("执行结果如下：");
    				System.out.println("-----------------");
    				System.out.println("姓名： "+"\t"+"之车：");
    				System.out.println("-----------------");
    				while(rs.next()){
    					strUser=rs.getString("name");
    					strPwd=rs.getString("pwd");
    					System.out.println(strUser+"\t"+strPwd);
    				} 
    				rs.close();
    				con.close();
    			}
    			catch(Exception ex){
    				ex.printStackTrace();
    			}finally{
    				System.out.println("数据库数据成功获取！");
    			}
    		}
    	});
    }

}
